import Common from "./Common";
import UserInfo from "../UserInfo";
import HttpManager from "../manager/HttpManager";
import MiniGameInfo from "../MiniGameInfo";
import Define from "./Define";

// Learn TypeScript:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;

@ccclass
export default class WXHelper{

    isShow:boolean = false
    tex:cc.Texture2D = null;
    display:cc.Sprite = null;

    public static instance:WXHelper;
    initWXHelper(){
        WXHelper.instance = this;
        if(cc.sys.platform == cc.sys.WECHAT_GAME) {
            this.initOnShareAppMessage();
        }
    }

    initOnShareAppMessage(){
        wx.showShareMenu();

        let showStr:string = "陨石坠落，人间大炮一级准备"
        let shareRes:string = "texture/share02"
        if(Common.getRandom(0,3) != 0){
            showStr = "欺负我，拿我的意大利炮出来"
            shareRes = "texture/share01"
        }
        cc.loader.loadRes(shareRes,function(err,data){	
            wx.onShareAppMessage(function(res){		
                return {				
                    title: showStr,				
                    imageUrl: data.url,			
                    success(res){				
                        console.log("转发成功!!!")		
	
                    },fail(res){		
                        console.log("转发失败!!!")			
                    } 		
                }
            })	
        })  
    }

    //分享
    shareAppMessage(str:String,callBack:Function = null) 
    {
        if(cc.sys.platform == cc.sys.WECHAT_GAME){
            let showStr:string = "陨石坠落，人间大炮一级准备"
            let shareRes:string = "texture/share02"
            if(Common.getRandom(0,3) != 0){
                showStr = "欺负我，拿我的意大利炮出来"
                shareRes = "texture/share01"
            }
            cc.loader.loadRes(shareRes,function(err,data){	    
                wx.shareAppMessage({
                    title: showStr,
                    imageUrl:  data.url,
                    success(res){				
                        console.log("转发成功!!!")		
	
                    },fail(res){		
                        console.log("转发失败!!!")			
                    } 	
                });
                if(callBack != null){
                    callBack();
                }
            })  
        }
    }

    _updaetSubDomainCanvas () {
        if (this.tex == null) {
            return;
        }
        if(cc.sys.platform == cc.sys.WECHAT_GAME){
            var openDataContext = window.wx.getOpenDataContext();
            var sharedCanvas = openDataContext.canvas;
            this.tex.initWithElement(sharedCanvas);
            this.tex.handleLoadedTexture();
            this.display.spriteFrame = new cc.SpriteFrame(this.tex);
        }
    }

    update (dt) {
        if(this.isShow){
            this._updaetSubDomainCanvas();
        }
    }

    showView(name:string,tag:string = "-1"){
        if(cc.sys.platform == cc.sys.WECHAT_GAME){
            console.log("显示子域 name = " +name);
            if(this.tex != null){
                this.tex.destroy();
                this.tex = null;
            }
            this.tex = new cc.Texture2D();
            this.display.node.active = true;
            this.tex.width = 640;
            this.tex.height = 1136;
            this.isShow = true
            wx.postMessage({
                messageType: "showView",
                viewName:name,
                tag:tag
            })
        }
    }

    hideView(name:string){

        if(cc.sys.platform == cc.sys.WECHAT_GAME){
            this.isShow = false;
            if(this.tex != null){
                this.tex.destroy();
                this.tex = null;
            }
            if(this.display.spriteFrame != null){
                this.display.spriteFrame.destroy();
                this.display.spriteFrame = null;
            }
            this.display.node.active = false;
            wx.postMessage({
                messageType: "hideView",
                viewName:name
            })
        }
    }

    submitScore(){
        console.log("submitScore 00000000")
        HttpManager.getInstance().submitUserInfo();
        if(Common.totalShowScore > UserInfo.maxScore){
            UserInfo.maxScore = Common.totalShowScore;
        }   
        //暂时每次都提交处理版本更新问题
        let score:string = UserInfo.maxScore.toString();
        let testDate = new Date();
        let week:string =  Common.getYearWeek(testDate.getFullYear(),testDate.getMonth()+1,testDate.getDate()).toString();
        UserInfo.saveMaxScore();
        if(cc.sys.platform == cc.sys.WECHAT_GAME){
            wx.postMessage({
                messageType: "score",
                score:score,
                week:week
            });
        }
    }
    //微信检测更新
    static wxCheckUpdate(){
        if(cc.sys.platform != cc.sys.WECHAT_GAME){
            return
        }
        if (typeof wx.getUpdateManager === 'function') { // 请在使用前先判断是否支持
            const updateManager = wx.getUpdateManager()
            updateManager.onCheckForUpdate(function (res) {
                if(!res.hasUpdate){

                }else{
                    wx.showModal({
                        title: '更新提示',
                        content: '版本更新中请稍后！',
                        showCancel:false,
                        confirmText:"",
                        success: function (res) {
               
                        }
                    })
                }
              // 请求完新版本信息的回调
              console.log(res.hasUpdate)
            })
            
            updateManager.onUpdateReady(function () {
                console.log("wxCheckUpdate 444")
                wx.showModal({
                    title: '更新提示',
                    content: '新版本已经准备好，请重启应用！',
                    showCancel:false,
                    success: function (res) {
                    if (res.confirm) {
                            console.log("wxCheckUpdate aaa")
                        // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                            updateManager.applyUpdate()
                        }
                    }
                })
            })
            
            updateManager.onUpdateFailed(function () {
                // 新版本下载失败
                console.log("wxCheckUpdate 555")
            })
        }
    }

    //调用微信登录
    static wxLogin(){

        console.log(" wxLogin ssssssssssssssss")
        if(cc.sys.platform != cc.sys.WECHAT_GAME){
            console.log(" wxLogin ddddddddd   55d")
            return
        }

        console.log(" wxLogin dddddddddd")

        wx.getUserInfo({

            success: function(res) {
                console.log("getUserInfo success");
                console.log(res);
                var userInfo = res.userInfo
                UserInfo.nickName = userInfo.nickName
                UserInfo.avatarUrl = userInfo.avatarUrl

                wx.login({//调用获取用户openId
                    success: function (res) {
                        console.log(res);
                        console.log("login success")
                        console.log(res['code'])
                        HttpManager.getInstance().loginWX(res['code']);
                    },
                    fail: function (res){
                        console.log("login fail")
                    }
                })
            },fail: function (res){
                console.log("getUserInfo fail")
                WXHelper.wxLogin();
            },complete: function (res){
                console.log("getUserInfo complete")
            }
        })
    }

    //调用检测登录的状态
    static wxCheckLogin(isMainView:boolean = true){
        Common.isInMainViewLogin = isMainView
        console.log("wxCheckLogin aaaaaaaaaaaa ")
        if(cc.sys.platform != cc.sys.WECHAT_GAME){
            return
        }
        console.log("wxCheckLogin 111111111111111 ")

        wx.getSetting({
            success: function (res) {
              var authSetting = res.authSetting
              console.log(authSetting);
              if (authSetting['scope.userInfo'] === true) {
                // 用户已授权，可以直接调用相关 API
                console.log("resssssssssssssssss")
                
                WXHelper.wxLogin();
                
                console.log("用户已授权，可以直接调用相关 API")
              } else if (authSetting['scope.userInfo'] === false){
                // 用户已拒绝授权，再调用相关 API 或者 wx.authorize 会失败，需要引导用户到设置页面打开授权开关
                console.log("isMainView ========= "+isMainView);
                if(!isMainView){
                    console.log(" getSetting ssssssssssssssssssss");
                    wx.showModal({
                        title: '世界排行',
                        content: '是否需要获取世界排行？',
                        showCancel: true,//是否显示取消按钮
                        cancelText:"否",//默认是“取消”
                        cancelColor:'#000000',//取消文字的颜色
                        confirmText:"是",//默认是“确定”
                        confirmColor: '#000000',//确定文字的颜色
                        success: function (res) {
                           if (res.cancel) {
                              //点击取消,默认隐藏弹框
                           } else {
                            wx.openSetting({
                                success:(res)=>{
                                    console.log("授权结果..")
                                    console.log(res)
                                    console.log(res.authSetting["scope.userInfo"]);
                                    if(res.authSetting["scope.userInfo"]){
                                        console.log("openSetting success")
                                        WXHelper.wxLogin();
                                    }
                                },fail:(res)=>{
                                    console.log("openSetting fail")
                                }
                            })
                           }
                        },
                        fail: function (res) { },//接口调用失败的回调函数
                        complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
                     })
      
                }
                console.log("用户已拒绝授权，再调用相关 API 或者 wx.authorize 会失败，需要引导用户到设置页面打开授权开关")
              } else {
                // 未询问过用户授权，调用相关 API 或者 wx.authorize 会弹窗询问用户
                if(!isMainView){
                    wx.authorize({
                        scope: 'scope.userInfo',
                        success: () => {
                            console.log('authorize success')
                            WXHelper.wxLogin();
                        },
                        fail:()=>{
                            console.log('authorize fail')
                        },
                    })
                }
                console.log("未询问过用户授权，调用相关 API 或者 wx.authorize 会弹窗询问用户")
              }
            }
        })
    }

    public static createImage(avatarUrl,spFace:cc.Sprite) {
        if (CC_WECHATGAME) {
            try {
                let image = wx.createImage();
                image.onload = () => {
                    try {
                        let texture = new cc.Texture2D();
                        texture.initWithElement(image);
                        texture.handleLoadedTexture();
                        spFace.spriteFrame = new cc.SpriteFrame(texture);
                    } catch (e) {
                        cc.log(e);
                        spFace.node.active = false;
                    }
                };
                image.src = avatarUrl;
            } catch (e) {
                cc.log(e);
                spFace.node.active = false;
            }
        } else {
            cc.loader.load({
                url: avatarUrl, type: 'jpg'
            }, (err, texture) => {
                spFace.spriteFrame = new cc.SpriteFrame(texture);
            });
        }
    }

    public static bannerAd = null;
    private static bannerAdId = "adunit-b1e29e0c371087b3" //banner_home
    public static showBannder(isShow){

        if(Define.gameId == "002"){
            //TODO :这里赋值 新的广告id
            return
        }
        if(cc.sys.platform != cc.sys.WECHAT_GAME){
            return
        }
        let screenHeight = wx.getSystemInfoSync().screenHeight;
        let screenWidth = wx.getSystemInfoSync().screenWidth;
       
        let bannerWidth:number = 300
        let bannerHeight:number = 80
    
        console.log("showBannder isShow = " +isShow)
       
        if(isShow){

            if(WXHelper.bannerAd == null){
                WXHelper.bannerAd = wx.createBannerAd({
                    adUnitId: WXHelper.bannerAdId,
                    style: {
                        left: (screenWidth-bannerWidth)*0.5,
                        top: screenHeight - bannerHeight,
                        width: bannerWidth
                    }
                })
                WXHelper.bannerAd.onLoad(() => {
                    console.log('banner 广告加载成功')

                })
                WXHelper.bannerAd.onError(err => {
                    console.log("showBannder onError = ")
                    console.log(err)
                  })
            }

            WXHelper.bannerAd.show().catch(err => console.log(err))
            WXHelper.bannerAd.onResize(function (res){
                WXHelper.bannerAd.style.top = screenHeight - WXHelper.bannerAd.style.realHeight;
            });
            
        }else{
            if(WXHelper.bannerAd != null){
                WXHelper.bannerAd.destroy();
                WXHelper.bannerAd = null
            }
        }
    }

    // video_fuhuo
    // adunit-68b829d3ac23ef00
    // 激励式视频
    public static isLoadVideoSuccessful:boolean = false  //广告加载是否成功 会出现加载失败的情况
    public static video = null;
    private static videoId = "adunit-68b829d3ac23ef00" 
    private static videoCallBack:Function;
    public static initRewardedVideoAd(){
        if(Define.gameId == "002"){
             //TODO :这里赋值 新的广告id
            return
        }
        if(cc.sys.platform != cc.sys.WECHAT_GAME){
            return
        }
        console.log("initRewardedVideoAd   000")
        WXHelper.video = wx.createRewardedVideoAd({ adUnitId: WXHelper.videoId})
        WXHelper.video.onError(function (errMsg){
            console.log("广告播放失败")
            WXHelper.videoCallBack(2)
            //videoCallBack.runWith(0)
        });

        WXHelper.video.onLoad(() => {
            console.log('激励视频 广告加载成功')
            WXHelper.isLoadVideoSuccessful = true
        })
        console.log("initRewardedVideoAd   111")
        
        WXHelper.video.onClose(function (res):void 
        {
            WXHelper.isLoadVideoSuccessful = false
            if (res.isEnded) 
            {
                console.log("广告播放成功")
                WXHelper.videoCallBack(1)
                //videoCallBack.runWith(1)
            }
            else
            {
                console.log("广告播放失败")
                WXHelper.videoCallBack(0)
                //videoCallBack.runWith(0)
            }
        });
    }

    //展示广告
    public static showVideo(callBack:Function){
        if(cc.sys.platform != cc.sys.WECHAT_GAME){
            return
        }
        if(!WXHelper.isLoadVideoSuccessful){
            console.log("广告加载失败")
            return;
        }
        console.log("showVideo   111")
        WXHelper.videoCallBack = callBack
        WXHelper.video.show().catch(err => console.log(err)).then(() => console.log('激励视频 广告显示'))
    }

    //短震动
    public static brateShort(){
        if(cc.sys.platform != cc.sys.WECHAT_GAME){
            return
        }
        if(UserInfo.brate != 1){
            return
        }
        wx.vibrateShort({})
    }
    //震动
    public static brateLong(){
        if(cc.sys.platform != cc.sys.WECHAT_GAME){
            return
        }
        if(UserInfo.brate != 1){
            return
        }
        wx.vibrateLong({})
    }

    static jumpToMiniProgram(appId:string){

        wx.navigateToMiniProgram({
            appId: appId,
            success(res) {
            // 打开成功
                console.log("success 666")
                console.log(res)
            },
            fail(res){
                console.log("fail 666")
                console.log(res)
            },complete(){
                console.log("complete 666")
            }

        })
    }
}
